package com.activity;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.misc.Tool;

public class RegisterActivity extends Activity {
	// constant
	public static final int REGISTER_INTERACT = 101;
	public static final int COMPLETE_REGISTER_INTERACT = 1;
	public static final int FOUND_PHONE_NUMBER_IS_DUPLICATED = 2;
	
	// field
	EditText etPhoneNumber, etPassword, etUserName;
	Button btnAvatar;
	Button btnFinishRegister;
	Bitmap bitmap;
	Boolean isPhoneNumberFilled = false, isPasswordFilled = false, isUserNameFilled = false;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_page);
		bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.default_avatar)).getBitmap();
		
		etPhoneNumber = (EditText) findViewById(R.id.etPhoneNumber);
		etPassword = (EditText) findViewById(R.id.etPassword);
		etUserName = (EditText) findViewById(R.id.etUserName);
		btnFinishRegister = (Button) findViewById(R.id.btnFinishRegister);
		
		etPhoneNumber.addTextChangedListener(new TextWatcher() {
	        public void onTextChanged(CharSequence s, int start, int before, int count) {
	        	isPhoneNumberFilled = !TextUtils.isEmpty(s);
				btnFinishRegister.setEnabled(isPhoneNumberFilled && isPasswordFilled && isUserNameFilled);
	        }
	        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	        }
	        public void afterTextChanged(Editable s) {
	        }
	    });
		etPassword.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				isPasswordFilled = !TextUtils.isEmpty(s);
				btnFinishRegister.setEnabled(isPhoneNumberFilled && isPasswordFilled && isUserNameFilled);
			}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			public void afterTextChanged(Editable s) {
			}
		});
		etUserName.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				isUserNameFilled = !TextUtils.isEmpty(s);
				btnFinishRegister.setEnabled(isPhoneNumberFilled && isPasswordFilled && isUserNameFilled);
			}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			public void afterTextChanged(Editable s) {
			}
		});
		
		btnAvatar = (Button) findViewById(R.id.btnAvatar);
		btnAvatar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				intent.putExtra("return-data", true);
				startActivityForResult(intent, 0);
			}
		});
		
		btnFinishRegister.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				register();
			}
		});
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0 && intent != null) {
			bitmap = intent.getParcelableExtra("data");
			Matrix matrix = new Matrix();
			matrix.postScale(150 / (float) bitmap.getWidth(), 130 / (float) bitmap.getHeight());
			btnAvatar.setBackgroundDrawable(new BitmapDrawable(Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true)));
			btnAvatar.setHint("");
		}
	}
	
	
	void register() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Socket socket = null;
				DataOutputStream dos = null;
				DataInputStream dis = null;
				try {
					socket = new Socket(MainActivity.SERVER_IP, 9999);
					dos = new DataOutputStream(socket.getOutputStream());
					dis = new DataInputStream(socket.getInputStream());
					dos.writeInt(RegisterActivity.REGISTER_INTERACT);
					dos.writeLong(Long.parseLong(etPhoneNumber.getText().toString()));
					dos.writeUTF(etPassword.getText().toString());
					dos.writeUTF(etUserName.getText().toString());
					Tool.sendByteArray(dos, Tool.bitmap2ByteArray(bitmap));
					
					if(dis.readBoolean())
						mHandler.sendEmptyMessageDelayed(COMPLETE_REGISTER_INTERACT, 0);
					else
						mHandler.sendEmptyMessageDelayed(FOUND_PHONE_NUMBER_IS_DUPLICATED, 0);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					try {
						dis.close();
						dos.close();
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message message) {
			if(message.what == COMPLETE_REGISTER_INTERACT) {
				setResult(RESULT_OK);
				finish();
			} else if(message.what == FOUND_PHONE_NUMBER_IS_DUPLICATED) {
				Toast.makeText(RegisterActivity.this, "this phone number is registered, please choose another number", Toast.LENGTH_LONG).show();
			}
		}
	};
}
